package com.aiyige.page.main;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.view.ViewPager;
import android.support.v7.app.AlertDialog;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.TextView;

import com.aiyige.MyApp;
import com.aiyige.R;
import com.aiyige.arouter.Router;
import com.aiyige.arouter.config.ARouterConfig;
import com.aiyige.arouter.eventbus.EventMainPageRouter;
import com.aiyige.base.BaseActivity;
import com.aiyige.base.db.table.AdModel;
import com.aiyige.base.eventbus.EventKickOff;
import com.aiyige.base.eventbus.EventLogin;
import com.aiyige.base.eventbus.EventNewMessageChanged;
import com.aiyige.base.eventbus.EventSelectRegion;
import com.aiyige.base.eventbus.EventTapBottomItemRefresh;
import com.aiyige.configs.MyConfig;
import com.aiyige.location.LocationService;
import com.aiyige.location.LocationUtil;
import com.aiyige.location.model.LocationData;
import com.aiyige.location.model.RegionData;
import com.aiyige.model.User;
import com.aiyige.page.advertisement.util.AdUtil;
import com.aiyige.page.login.model.impl.LoginManager;
import com.aiyige.page.main.adapter.MainViewPagerAdapter;
import com.aiyige.page.my.message.util.MessageUtil;
import com.aiyige.page.pay.util.PayUtil;
import com.aiyige.page.publish.publishresult.PublishResult;
import com.aiyige.page.webview.PreloadWebView;
import com.aiyige.track.annotation.Track;
import com.aiyige.utils.AccountUtil;
import com.aiyige.utils.DummyDataUtil;
import com.aiyige.utils.StringUtils;
import com.aiyige.utils.ToastX;
import com.aiyige.utils.crash.CrashUtils;
import com.alibaba.android.arouter.facade.annotation.Autowired;
import com.alibaba.android.arouter.facade.annotation.Route;
import com.alibaba.android.arouter.launcher.ARouter;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

@Track("Android主页")
@Route(path = ARouterConfig.MainPage)
public class MainPage extends BaseActivity {
    public static final String TAG = MainPage.class.getSimpleName();
    public static final int REQUEST_CODE_PUBLISH = 1;
    public static final int COMMUNICATE_PAGE_INDEX = 2;
    @BindView(R.id.mainVp)
    ViewPager mainVp;
    @BindView(R.id.homeLayout)
    LinearLayout homeLayout;
    @BindView(R.id.messageLayout)
    ViewGroup messageLayout;
    @BindView(R.id.findLayout)
    LinearLayout findLayout;
    @BindView(R.id.myLayout)
    LinearLayout myLayout;
    @BindView(R.id.coreBtn)
    ImageView coreBtn;
    @BindView(R.id.unReadMessageTv)
    TextView unReadMessageTv;
    long exitTimestamp = 0;
    BroadcastReceiver receiver;
    IntentFilter intentFilter;
    @BindView(R.id.homeRefreshProgressBar)
    ProgressBar homeRefreshProgressBar;
    @BindView(R.id.messageRefreshProgressBar)
    ProgressBar messageRefreshProgressBar;
    @BindView(R.id.findRefreshProgressBar)
    ProgressBar findRefreshProgressBar;
    @BindView(R.id.myRefreshProgressBar)
    ProgressBar myRefreshProgressBar;
    @Autowired
    AdModel adModel = null;
    boolean homeRefreshing = false;
    boolean findRefreshing = false;
    boolean messageRefreshing = false;
    boolean myRefreshing = false;
    @BindView(R.id.preloadWebView)
    PreloadWebView preloadWebView;
    @Autowired
    int index = 0;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.page_main);
        ButterKnife.bind(this);
        ARouter.getInstance().inject(this);
        exitTimestamp = 0;
        mainVp.setAdapter(new MainViewPagerAdapter(getSupportFragmentManager()));
        mainVp.setOffscreenPageLimit(mainVp.getAdapter().getCount());
        selectHome();
        AdUtil.playAd(this, adModel);
//        mainVp.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
//            @Override
//            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
//
//            }
//
//            @Override
//            public void onPageSelected(int position) {
//                switch (position) {
//                    case 0:
//                        selectHome();
//                        break;
//                    case 1:
//                        selectMessage();
//                        break;
//                    case 2:
//                        selectFind();
//                        break;
//                    case 3:
//                        selectMy();
//                        break;
//                    default:
//                        selectHome();
//                        break;
//                }
//            }
//
//            @Override
//            public void onPageScrollStateChanged(int state) {
//
//            }
//        });
        receiver = new BroadcastReceiver() {
            @Override
            public void onReceive(Context context, Intent intent) {
                String action = "";
                try {
                    action = intent.getAction();
                } catch (Exception e) {

                }

                switch (action) {
                    case LocationService.ACTION_LOCATION_FINISH: {
                        LocationData locationData = null;
                        try {
                            locationData = intent.getParcelableExtra(LocationService.EXTRA_LOCATION_DATA);
                        } catch (Exception e) {

                        }
                        if (locationData != null && locationData.isSuccess()) {
                            if (LocationUtil.getCurrentUserSelectRegion() != null && !locationData.getCity().contains(LocationUtil.getCurrentUserSelectRegion().getCityName())) {
                                final LocationData finalLocationData = locationData;
                                new AlertDialog.Builder(MainPage.this)
                                        .setMessage(String.format(StringUtils.getString(R.string.location_alert_message), finalLocationData.getCity()))
                                        .setPositiveButton(R.string.confirm, new DialogInterface.OnClickListener() {
                                            @Override
                                            public void onClick(DialogInterface dialog, int which) {
                                                LocationUtil.setCurrentUserSelectRegion(new RegionData(finalLocationData.getCity(), finalLocationData.getCountry() + " " + finalLocationData.getProvince() + " " + finalLocationData.getCity(), DummyDataUtil.getCityId(finalLocationData.getProvince(), finalLocationData.getCity())));
                                                EventBus.getDefault().post(new EventSelectRegion());
                                            }
                                        })
                                        .setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener() {
                                            @Override
                                            public void onClick(DialogInterface dialog, int which) {
                                            }
                                        })
                                        .create()
                                        .show();
                            } else {
                                LocationUtil.setCurrentUserSelectRegion(new RegionData(locationData.getCity(), locationData.getCountry() + " " + locationData.getProvince() + " " + locationData.getCity(), DummyDataUtil.getCityId(locationData.getProvince(), locationData.getCity())));
                                EventBus.getDefault().post(new EventSelectRegion());
                            }
                        }
                        break;
                    }
                    default:
                        break;
                }


            }
        };
        intentFilter = new IntentFilter();
        intentFilter.addAction(LocationService.ACTION_LOCATION_FINISH);
        LocationService.startLocation(this);
//        initCrashIp();
        LoginManager.getInstance().IMLogin();
        updateUnReadMessageView();
        preloadWebView.onCreate();
        Router.registerRouterEventBus(this);
        PayUtil.checkUnpaid(this);// 检查未支付手续费
        EventBus.getDefault().register(this);
    }

    @Override
    protected void onResume() {
        super.onResume();
        registerReceiver(receiver, intentFilter);
    }

    @Override
    protected void onPause() {
        try {
            unregisterReceiver(receiver);
        } catch (Exception e) {

        }
        super.onPause();
    }

    @Override
    protected void onDestroy() {
        EventBus.getDefault().unregister(this);
        preloadWebView.onDestroy();
        Router.unregisterRouterEventBus(this);
        super.onDestroy();
    }

    public void startRefreshHome() {
        if (homeRefreshing) return;
        homeRefreshing = true;
        //homeRefreshProgressBar.setVisibility(View.VISIBLE);
        EventBus.getDefault().post(EventTapBottomItemRefresh.newBuilder()
                .actionType(EventTapBottomItemRefresh.ACTION_TYPE_PRE_REFRESH)
                .itemType(EventTapBottomItemRefresh.ITEM_TYPE_HOME)
                .build());
    }

    public void startRefreshMessage() {
        if (messageRefreshing) return;
        messageRefreshing = true;
        //messageRefreshProgressBar.setVisibility(View.VISIBLE);
        EventBus.getDefault().post(EventTapBottomItemRefresh.newBuilder()
                .actionType(EventTapBottomItemRefresh.ACTION_TYPE_PRE_REFRESH)
                .itemType(EventTapBottomItemRefresh.ITEM_TYPE_MESSAGE)
                .build());
    }

    public void startRefreshFind() {
        if (findRefreshing) return;
        findRefreshing = true;
        //findRefreshProgressBar.setVisibility(View.VISIBLE);
        EventBus.getDefault().post(EventTapBottomItemRefresh.newBuilder()
                .actionType(EventTapBottomItemRefresh.ACTION_TYPE_START_REFRESH)//TODO:记得换成START_REFRESH
                .itemType(EventTapBottomItemRefresh.ITEM_TYPE_FIND)
                .build());
    }

    public void startRefreshMy() {
        if (myRefreshing) return;
        myRefreshing = true;
        //myRefreshProgressBar.setVisibility(View.VISIBLE);
        EventBus.getDefault().post(EventTapBottomItemRefresh.newBuilder()
                .actionType(EventTapBottomItemRefresh.ACTION_TYPE_START_REFRESH)
                .itemType(EventTapBottomItemRefresh.ITEM_TYPE_MY)
                .build());
    }

    public void stopRefreshHome() {
        homeRefreshing = false;
        homeRefreshProgressBar.setVisibility(View.INVISIBLE);
    }

    public void stopRefreshMessage() {
        messageRefreshing = false;
        messageRefreshProgressBar.setVisibility(View.INVISIBLE);
    }

    public void stopRefreshFind() {
        findRefreshing = false;
        findRefreshProgressBar.setVisibility(View.INVISIBLE);
    }

    public void stopRefreshMy() {
        myRefreshing = false;
        myRefreshProgressBar.setVisibility(View.INVISIBLE);
    }


    @OnClick({R.id.homeLayout, R.id.messageLayout, R.id.findLayout, R.id.myLayout, R.id.coreBtn})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.locationLayout:
                break;
            case R.id.homeLayout:
                if (!currentHome()) {
                    selectHome();
                } else {
                    startRefreshHome();
                }
                break;
            case R.id.messageLayout:
                if (!currentMessage()) {
                    selectMessage();
                } else {
                    startRefreshMessage();
                }
                break;
            case R.id.findLayout:
                if (!currentFind()) {
                    selectFind();
                } else {
                    startRefreshFind();
                }
                break;
            case R.id.myLayout:
                if (!currentMy()) {
                    selectMy();
                } else {
                    //startRefreshMy();
                }
                break;
            case R.id.coreBtn:
                ARouter.getInstance()
                        .build(ARouterConfig.PublishEntryPage)
                        .withFlags(Intent.FLAG_ACTIVITY_NO_ANIMATION)
                        .navigation(this, REQUEST_CODE_PUBLISH);
                break;
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        switch (requestCode) {
            case REQUEST_CODE_PUBLISH:
                PublishResult publishResult = PublishResult.obtainPublishResult(data);
                PublishResult.handlePublishResult(this, publishResult);
                break;
            default:
                super.onActivityResult(requestCode, resultCode, data);
                break;
        }
    }

    public void selectHome() {
        resetBottomBar();
        mainVp.setCurrentItem(0, false);
        homeLayout.setSelected(true);
    }

    public void selectMessage() {
        if (AccountUtil.isLogin()) {
            resetBottomBar();
            mainVp.setCurrentItem(2, false);
            messageLayout.setSelected(true);
            updateUnReadMessageView();
        } else {
            ARouter.getInstance().build(ARouterConfig.LoginPage).navigation();
        }
    }

    public void selectFind() {
        resetBottomBar();
        mainVp.setCurrentItem(1, false);
        findLayout.setSelected(true);
    }

    public void selectMy() {
        resetBottomBar();
        mainVp.setCurrentItem(3, false);
        myLayout.setSelected(true);
    }

    private void resetBottomBar() {
        homeLayout.setSelected(false);
        messageLayout.setSelected(false);
        findLayout.setSelected(false);
        myLayout.setSelected(false);
    }


    public boolean currentHome() {
        return mainVp.getCurrentItem() == 0;
    }

    public boolean currentMessage() {
        return mainVp.getCurrentItem() == 2;
    }

    public boolean currentFind() {
        return mainVp.getCurrentItem() == 1;
    }

    public boolean currentMy() {
        return mainVp.getCurrentItem() == 3;
    }

    @Override
    public void onBackPressed() {
        if ((System.currentTimeMillis() - exitTimestamp) > MyConfig.EXIT_TIMEOUT) {
            ToastX.show(R.string.exit_tip);
            exitTimestamp = System.currentTimeMillis();
        } else {
            super.onBackPressed();
            MyApp.getInstance().quit();
        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onEvent(EventNewMessageChanged event) {
//        if (currentMessage()) {
//            MessageUtil.clearNewMessage(MessageUtil.MESSAGE_LEVEL_MAIN);
//        }
        updateUnReadMessageView();
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onEvent(EventKickOff eventKickOff) {
        ToastX.show("您的账号已在其他设备上登录");
        ARouter.getInstance()
                .build(ARouterConfig.MainPage)
                .withFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP)
                .navigation(this);
    }

    public void updateUnReadMessageView() {
        MessageUtil.MessageCount messageCount = MessageUtil.getNewMessageCount(MessageUtil.MESSAGE_LEVEL_MAIN);
        long totalMessageNum = MessageUtil.getTotalNewMessageCount(messageCount);
        unReadMessageTv.setVisibility(totalMessageNum <= 0 ? View.INVISIBLE : View.VISIBLE);
        unReadMessageTv.setText(String.valueOf(Math.min(totalMessageNum, 99)));
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onEvent(EventTapBottomItemRefresh event) {
        if (event.getActionType() == EventTapBottomItemRefresh.ACTION_TYPE_START_REFRESH
                || event.getActionType() == EventTapBottomItemRefresh.ACTION_TYPE_PRE_REFRESH)
            return;
        switch (event.getItemType()) {
            case EventTapBottomItemRefresh.ITEM_TYPE_FIND:
                stopRefreshFind();
                break;
            case EventTapBottomItemRefresh.ITEM_TYPE_HOME:
                stopRefreshHome();
                break;
            case EventTapBottomItemRefresh.ITEM_TYPE_MESSAGE:
                stopRefreshMessage();
                break;
            case EventTapBottomItemRefresh.ITEM_TYPE_MY:
                stopRefreshMy();
                break;
        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onEvent(EventLogin eventLogin) {
        User user = AccountUtil.getCurrentUser();
        if (user.isNewUser()) {
            user.setNewUser(false);
            AccountUtil.updateCurrentUser(user);
            ARouter.getInstance()
                    .build(ARouterConfig.SelectUserInterestPage)
                    .navigation();
        }
        LoginManager.getInstance().IMLogin();
        PayUtil.checkUnpaid(this);// 检查未支付手续费
    }

    /**
     * 初始化ip
     */
    private void initCrashIp() {
        Handler handler = new Handler() {
            @Override
            public void handleMessage(Message msg) {
                CrashUtils.getNetIp();
            }
        };
        handler.sendEmptyMessageDelayed(0, 5000);
    }

    public int getCurrentItem() {
        try {
            return mainVp.getCurrentItem();
        } catch (Exception e) {
            return -1;
        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN, sticky = true)
    public void onEvent(EventMainPageRouter event) {
        Router.eventBus.removeStickyEvent(event);
        switch (event.getJumpIndex()) {
            case 0:
                selectHome();
                break;
            case 1:
                selectFind();
                break;
            case 2:
                selectMessage();
                break;
            case 3:
                selectMy();
                break;
        }
    }
}
